<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="商品名称">
          <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="queryParams.categoryId" placeholder="请选择商品分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleAdd">添加商品</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-table
      v-loading="loading"
      :data="goodsList"
      border
      style="width: 100%"
    >
      <el-table-column prop="goodsId" label="ID" width="80" align="center" />
      <el-table-column prop="goodsName" label="商品名称" min-width="120" />
      <el-table-column label="商品图片" width="100" align="center">
        <template #default="scope">
          <el-image 
            v-if="scope.row.image"
            :src="getImageUrl(scope.row.image)" 
            style="width: 60px; height: 60px"
            :preview-src-list="[getImageUrl(scope.row.image)]"
            fit="cover"
          />
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="分类" width="100" />
      <el-table-column prop="goodsPrice" label="价格" width="80" align="center" />
      <el-table-column prop="sellStatus" label="库存" width="60" align="center" />
      <el-table-column prop="userName" label="发布人" width="100" />
      <el-table-column prop="createTime" label="发布时间" width="140" />
      <el-table-column label="上架状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'info'">
            {{ scope.row.status === '0' ? '上架中' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="setIndex" label="推荐" width="80" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.setIndex === '1' ? 'warning' : 'info'">
            {{ scope.row.setIndex === '1' ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            v-if="scope.row.status === '0'" 
            type="warning" 
            size="small" 
            @click="handleOffShelve(scope.row)"
          >
            下架商品
          </el-button>
          <el-button 
            v-else 
            type="success" 
            size="small" 
            @click="handleOnShelve(scope.row)"
          >
            上架商品
          </el-button>
          <el-button 
            v-if="scope.row.setIndex === '0'" 
            type="warning" 
            size="small" 
            @click="handleRecommend(scope.row, '1')"
          >
            推荐
          </el-button>
          <el-button 
            v-else 
            type="info" 
            size="small" 
            @click="handleRecommend(scope.row, '0')"
          >
            取消推荐
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDeleteGoods(scope.row)"
          >
            永久删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 商品表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="650px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择商品分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input-number v-model="form.goodsPrice" :min="0" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="商品库存" prop="sellStatus">
          <el-input-number v-model="form.sellStatus" :min="0" :precision="0" />
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :limit="1"
            list-type="picture"
            :file-list="fileList"
          >
            <el-button type="primary">选择图片</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过2MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品简介" prop="goodsDesc">
          <el-input
            v-model="form.goodsDesc"
            type="textarea"
            :rows="4"
            placeholder="请输入商品简介"
          />
        </el-form-item>
        <el-form-item label="商品地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入商品地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getGoodsPage, saveOrUpdateGoods, deleteGoods } from '@/api/goods'
import { getCategoryList } from '@/api/category'
import { handlePageResponse } from '@/utils/pagination'

// 商品列表
const goodsList = ref([])
// 分类选项
const categoryOptions = ref([])
// 总数据量
const total = ref(0)
// 加载状态
const loading = ref(false)
// 提交加载状态
const submitLoading = ref(false)
// 表单对话框可见状态
const dialogVisible = ref(false)
// 表单对话框标题
const dialogTitle = ref('添加商品')
// 表单引用
const formRef = ref(null)
// 图片上传文件列表
const fileList = ref([])

// 上传URL
const uploadUrl = '/api/file/uploadImage/goods' // 使用goods作为上传的前缀

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  goodsName: '',
  categoryId: null
})

// 表单数据
const form = reactive({
  goodsId: null,
  goodsName: '',
  categoryId: null,
  goodsPrice: 0,
  sellStatus: 0,
  image: '',
  goodsDesc: '',
  address: '',
  status: '0',
  setIndex: '0'
})

// 表单验证规则
const rules = {
  goodsName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  goodsPrice: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  sellStatus: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ],
  goodsDesc: [
    { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
  ]
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  return `/api/file/download?fileName=${imagePath}`
}

// 初始化数据
onMounted(async () => {
  await Promise.all([
    fetchData(),
    fetchCategoryOptions()
  ])
})

// 获取商品列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getGoodsPage(queryParams)
    const { list, total: totalCount } = handlePageResponse(res)
    goodsList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('获取商品列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取分类选项
const fetchCategoryOptions = async () => {
  try {
    const res = await getCategoryList()
    categoryOptions.value = res.data || []
  } catch (error) {
    console.error('获取分类选项失败:', error)
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchData()
}

// 重置查询
const resetQuery = () => {
  queryParams.goodsName = ''
  queryParams.categoryId = null
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  fetchData()
}

// 处理添加商品
const handleAdd = () => {
  dialogTitle.value = '添加商品'
  resetForm()
  fileList.value = []
  dialogVisible.value = true
}

// 处理编辑商品
const handleEdit = (row) => {
  dialogTitle.value = '编辑商品'
  resetForm()
  Object.assign(form, row)
  
  // 设置图片文件列表
  fileList.value = row.image ? [{
    name: row.image.split('/').pop(),
    url: getImageUrl(row.image)
  }] : []
  
  dialogVisible.value = true
}

// 上传前验证
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG/PNG格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response, file) => {
  if (response.code === 200) {
    form.image = response.data
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 上传失败回调
const handleUploadError = () => {
  ElMessage.error('图片上传失败')
}

// 处理下架商品
const handleOffShelve = (row) => {
  ElMessageBox.confirm(
    `确认下架商品 "${row.goodsName}" 吗？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 将status修改为1表示下架
      const updateData = { ...row, status: '1' }
      await saveOrUpdateGoods(updateData)
      ElMessage({
        type: 'success',
        message: '下架成功!'
      })
      await fetchData()
    } catch (error) {
      console.error('下架商品失败:', error)
    }
  }).catch(() => {
    // 取消操作
  })
}

// 处理上架商品
const handleOnShelve = (row) => {
  ElMessageBox.confirm(
    `确认上架商品 "${row.goodsName}" 吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      // 将status修改为0表示上架
      const updateData = { ...row, status: '0' }
      await saveOrUpdateGoods(updateData)
      ElMessage({
        type: 'success',
        message: '上架成功!'
      })
      await fetchData()
    } catch (error) {
      console.error('上架商品失败:', error)
    }
  }).catch(() => {
    // 取消操作
  })
}

// 处理推荐/取消推荐
const handleRecommend = (row, setIndex) => {
  const actionText = setIndex === '1' ? '推荐' : '取消推荐'
  ElMessageBox.confirm(
    `确认${actionText}商品 "${row.goodsName}" 吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      const updateData = { ...row, setIndex }
      await saveOrUpdateGoods(updateData)
      ElMessage({
        type: 'success',
        message: `${actionText}成功!`
      })
      await fetchData()
    } catch (error) {
      console.error(`${actionText}商品失败:`, error)
    }
  }).catch(() => {
    // 取消操作
  })
}

// 重置表单
const resetForm = () => {
  form.goodsId = null
  form.goodsName = ''
  form.categoryId = null
  form.goodsPrice = 0
  form.sellStatus = 0
  form.image = ''
  form.goodsDesc = ''
  form.address = ''
  form.status = '0'
  form.setIndex = '0'
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      await saveOrUpdateGoods(form)
      ElMessage({
        type: 'success',
        message: form.goodsId ? '更新成功!' : '添加成功!'
      })
      dialogVisible.value = false
      await fetchData()
    } catch (error) {
      console.error('保存商品失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}

// 处理删除商品
const handleDeleteGoods = (row) => {
  ElMessageBox.confirm(
    `确认要删除商品 "${row.goodsName}" 吗？此操作将永久删除该商品，无法恢复！`,
    '警告',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteGoods(row.goodsId)
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      // 刷新商品列表
      fetchData()
    } catch (error) {
      console.error('删除商品失败:', error)
      ElMessage({
        type: 'error',
        message: '删除失败，请稍后再试'
      })
    }
  }).catch(() => {
    // 用户取消删除操作
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.el-upload {
  width: 100%;
}

.upload-demo {
  margin-bottom: 10px;
}
</style> 